﻿using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Autodesk.AutoCAD.ApplicationServices;

namespace AutoCADDotNetLibrary
{
    /// <summary>
    /// CAD路径
    /// </summary>
    public static class CADPath
    {
        /// <summary>
        /// menuname系统变量，由于我的cad2012得到的结果全是小写的（不知道为什么，特此做了如下处理）
        /// </summary>
        public static string AcadCUIX
        {
            get
            {
                string name = Application.GetSystemVariable("menuname").ToString();

                string[] dirNames = Regex.Matches(name, @"\\([^\\]+)").Cast<Match>().Select(x => x.Value).ToArray();
                string[] newName = new string[] { Directory.GetDirectoryRoot(name) };

                for (int i = 0; i < dirNames.Length - 1; i++)
                {
                    newName = getDirName(newName, dirNames[i]);
                }

                newName = newName.SelectMany(dirc => Directory.GetFiles(dirc)
                .Where(x => "\\" + Path.GetFileNameWithoutExtension(x).ToLower() == dirNames[dirNames.Length - 1].ToLower())
                .Where(x => Path.GetExtension(x).ToUpper() == ".CUIX")).ToArray();

                string[] getDirName(string[] dir, string fileName)
                {
                    return dir.SelectMany(dirc => Directory.GetDirectories(dirc).Where(x => "\\" + Path.GetFileName(x).ToLower() == fileName.ToLower())).ToArray();
                }


                if (newName.Length == 0)
                {
                    return null;
                }
                else
                {
                    return newName[0];
                }
            }
        }
    }
}
